<template>
  <!-- 商店管理页面 -->
  <div class="content">
    <div class="card">
      <text>商店名称：</text
      ><a-input v-model:value="shopInfo.name" placeholder="请输入饭堂名" />
      <text>轮播图: </text
      ><a-input-group compact style="width: 100%">
        <a-input
          v-model:value="shopInfo.banner_urls"
          placeholder="请输入轮播图url"
          style="width: calc(100% - 25%); text-align: left"
        ></a-input>
        <a-button @click="triggerUpload2" :loading="btnLoading2">上传</a-button>
        <a-upload
          :before-upload="beforeUpload"
          :max-count="5"
          v-model:file-list="fileList2"
          :multiple="true"
        >
          <a-button> 选择图片 </a-button>
        </a-upload>
      </a-input-group>

      <!-- <upload-outlined></upload-outlined> -->
      <!-- 点击上传按钮 -->

      <text>描述: </text
      ><a-input v-model:value="shopInfo.description" placeholder="请输入描述" />
      <text>图标: </text
      >
      <!-- <a-input v-model:value="shopInfo.icon_url" placeholder="请输入图标url" /> -->
      <a-input-group compact style="width: 100%">
        <a-input
          v-model:value="shopInfo.icon_url"
          placeholder="请输入图标url"
          style="width: calc(100% - 25%); text-align: left"
        ></a-input>
        <a-button @click="triggerUpload3" :loading="btnLoading3">上传</a-button>
        <a-upload
          :before-upload="beforeUpload"
          :max-count="1"
          v-model:file-list="fileList3"
          :multiple="true"
        >
          <a-button> 选择图片 </a-button>
        </a-upload>
      </a-input-group>

      <text>商店后厨图片: </text
      ><a-input v-model:value="shopInfo.kitchen" placeholder="请输入图标url" />

      <!-- 限制最大待上传的文件数量为 5 -->
      <!-- 添加选择文件后的回调和移除待上传文件的回调 -->
      <!-- <a-upload
                :before-upload="beforeUpload"
                :max-count="5"
                @remove="handleRemove"
            > -->
      <a-upload
        :before-upload="beforeUpload"
        :max-count="5"
        v-model:file-list="fileList"
        :multiple="true"
      >
        <a-button>
          <upload-outlined></upload-outlined>
          选择图片
        </a-button>
      </a-upload>
      <!-- 点击上传按钮 -->
      <a-button @click="triggerUpload" :loading="btnLoading">上传</a-button>

      <div class="btn">
        <a-button type="primary" @click="save">保存</a-button>
        <a-button type="primary" @click="reset">重置</a-button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import Qs from "qs";
import { Upload } from "ant-design-vue";
import { toRaw } from "@vue/reactivity";

export default {
  data() {
    return {
      shop_id: 0,
      shopInfo: {
        name: "",
        banner_urls: [],
        description: "",
        icon_url: "",
        kitchen: "",
      },
      bak: {},
      fileList: [],
      base64img: {},
      btnLoading: false,
      fileList2: [],
      btnLoading2: false,
      fileList3: [],
      btnLoading3: false
    };
  },

  mounted: function () {

// 判断是否登录
    if (!this.$store.state.is_login)
    {
        alert("未登录，请先登录!")
       this.$router.push('/');
       return;
    }

    // this.fileList = [];
    // 获取商店id
    this.shop_id = this.$store.state.shop_id;

    // 获取商店信息
    axios
      .get("/shop/getInfoByShopId", {
        params: {
          shop_id: this.shop_id,
        },
      })
      .then((res) => {
        this.shopInfo = res.data;
        let tmp_str = "";
        for (let index in this.shopInfo.banner_urls) {
          tmp_str += this.shopInfo.banner_urls[index].img_url + ",";
        }
        // 去掉最后一个逗号
        tmp_str = tmp_str.slice(0, tmp_str.length - 1);

        this.shopInfo.banner_urls = tmp_str;
        this.bak = { ...this.shopInfo };
        console.log(this.shopInfo);
        console.log(this.bak);
      });
  },

  methods: {
    save() {
      let obj = {
        need_parse: 1,
        shop_id: this.shop_id,
        name: this.shopInfo.name,
        banner_urls: this.shopInfo.banner_urls,
        description: this.shopInfo.description,
        icon_url: this.shopInfo.icon_url,
        kitchen: this.shopInfo.kitchen,
      };
      //   for (let index in this.img_append) {
      //     obj.kitchen.push(this.img_append[index]);
      //   }
      let post_val = Qs.stringify(obj);

      // 保存商店信息
      axios.post("/shop/modi_shopInfo", post_val).then((res) => {
        console.log(res.data.msg);
        if (res.data.msg === "success") {
          alert("保存成功");
          //   this.img_append = [];
        } else {
          alert("保存失败");
        }
      });
    },

    reset() {
      this.shopInfo = { ...this.bak };
      console.log(this.shopInfo);
    },

    getBase64(img, callback) {
      const reader = new FileReader(img, callback);
      reader.addEventListener("load", () => callback(reader.result));
      // ↑ 监听 reader 的 load 事件，触发时执行回调函数
      // 回调函数的作用就是将图片编码的base64字符串传给 base64img
      reader.readAsDataURL(img);
    },

    beforeUpload(file) {
      //   console.log(file);
      // 判断文件是否为图片格式
      const isImg = file.type === "image/jpeg" || file.type === "image/png";

      // 如果文件不是图片格式则禁止上传
      if (!isImg) {
        // Notice.error("只能上传 jpeg/jpg/png 格式的文件！");
        // ↑ Notice.error 是我自己写的 Notice 类的一个静态函数
        // 用的是 antdv 的 Notifiacation
        return Upload.LIST_IGNORE;
      }
      //   this.fileList.push(file);
      //   console.log("fileList: ", this.fileList);
      //   console.log(this.fileList[0]);
      // ↓ 获取所需要上传图片的 Base64 编码
      //   this.getBase64(this.fileList, (cb_img) => {
      //     // 将获取到的所要上传图片的 Base64 编码渲染到图片上
      //     this.base64img = cb_img;
      //   });
      return false;
    },

    triggerUpload() {
      const formData = new FormData();
      console.log("fileList: ", toRaw(this.fileList));
      // 对文件列表 判空
      if (this.fileList != null) {
        // DONE: 对于vue3中的proxy对象，要先使用toRaw获取到原始对象
        let tmp_list = toRaw(this.fileList);
        for (let i = 0; i < tmp_list.length; i++) {
          // DONE: 对于tmp_list数组，里面的元素中的originFileObj属性才是原始的文件对象
          formData.append("images", tmp_list[i].originFileObj);
          console.log("file: ", tmp_list[i].originFileObj);
        }
      } else {
        // Notice.error("文件不能为空！")
        console.log("文件为空");
        return Upload.LIST_IGNORE;
      }

      // ↓ 在上传过程中，按钮为 loading 状态
      this.btnLoading = true;
      console.log("formData------: ", formData.getAll("images"));
      axios
        .post("/shop/uploadImgMultiple", formData, {
          baseURL: "http://localhost:8082",
          headers: {
            "Content-Type": "multipart/form-data",
            transformRequest: [(data) => data],
          },
        })
        .then(
          (res) => {
            console.log(res.data);
            // ↓ 上传成功，按钮为默认状态

            this.btnLoading = false;
            // ↓ 获取上传成功后的图片 url
            const imgUrl = res.data.data.urls;

            // ↓ 将获取到的图片 url 赋值给 imgUrl
            console.log("imgUrl: ", imgUrl);
            // for (let index in imgUrl)
            // {
            //   this.img_append.push(imgUrl[index]);
            // }
            console.log("this.shopInfo.kitchen1: ", this.shopInfo.kitchen);
            let tmp_str = "";
            let tmpList = this.shopInfo.kitchen.split(",");

            let tmp_list = [];
            for (let i = 0; i < tmpList.length; i++) {
              if (tmpList[i] == "") continue;
              tmp_list.push(tmpList[i]);
            }
            // if (tmp_list == [])
            // {
            for (let index in imgUrl) {
              tmp_list.push(imgUrl[index]);
            }
            tmp_str = JSON.stringify(tmp_list);
            tmp_str = tmp_str.replaceAll("\"", "");
            this.shopInfo.kitchen = tmp_str.substring(1, tmp_str.length - 1);
            // }
            console.log("this.shopInfo.kitchen2: ", this.shopInfo.kitchen);
            // let tmp_str = JSON.stringify(this.shopInfo.kitchen);
            // if (tmp_str != undefined){
            //     this.shopInfo.kitchen = tmp_str + JSON.stringify(this.img_append);
            // }
            // else
            // {
            //     this.shopInfo.kitchen = JSON.stringify(this.img_append);
            // }
            alert("上传成功");
          },
          () => {
            alert("上传失败");
            this.btnLoading = false;
          }
        );
    },

    triggerUpload2(){
      const formData = new FormData();
      console.log("fileList2: ", toRaw(this.fileList2));
      // 对文件列表 判空
      if (this.fileList2 != null) {
        // DONE: 对于vue3中的proxy对象，要先使用toRaw获取到原始对象
        let tmp_list = toRaw(this.fileList2);
        for (let i = 0; i < tmp_list.length; i++) {
          // DONE: 对于tmp_list数组，里面的元素中的originFileObj属性才是原始的文件对象
          formData.append("images", tmp_list[i].originFileObj);
          console.log("file: ", tmp_list[i].originFileObj);
        }
      } else {
        // Notice.error("文件不能为空！")
        console.log("文件为空");
        return Upload.LIST_IGNORE;
      }

      // ↓ 在上传过程中，按钮为 loading 状态
      this.btnLoading2 = true;
      console.log("formData------: ", formData.getAll("images"));
      axios
        .post("/shop/uploadImgMultiple", formData, {
          baseURL: "http://localhost:8082",
          headers: {
            "Content-Type": "multipart/form-data",
            transformRequest: [(data) => data],
          },
        })
        .then(
          (res) => {
            console.log(res.data);
            // ↓ 上传成功，按钮为默认状态

            this.btnLoading2 = false;
            // ↓ 获取上传成功后的图片 url
            const imgUrl = res.data.data.urls;

            // ↓ 将获取到的图片 url 赋值给 imgUrl
            console.log("imgUrl: ", imgUrl);
            let tmp_str = "";
            let tmpList = this.shopInfo.banner_urls.split(",");

            let tmp_list = [];
            for (let i = 0; i < tmpList.length; i++) {
              if (tmpList[i] == "") continue;
              tmp_list.push(tmpList[i]);
            }
            // if (tmp_list == [])
            // {
            for (let index in imgUrl) {
              tmp_list.push(imgUrl[index]);
            }
            tmp_str = JSON.stringify(tmp_list);
            tmp_str = tmp_str.replaceAll("\"", "");
            this.shopInfo.banner_urls = tmp_str.substring(1, tmp_str.length - 1);
            // }
            console.log("this.shopInfo.banner_urls: ", this.shopInfo.banner_urls);
            alert("上传成功");
          },
          () => {
            alert("上传失败");
            this.btnLoading = false;
          }
        );
    },

    triggerUpload3(){
      const formData = new FormData();
      console.log("fileList3: ", toRaw(this.fileList3));
      // 对文件列表 判空
      if (this.fileList3 != null) {
        // DONE: 对于vue3中的proxy对象，要先使用toRaw获取到原始对象
        let tmp_list = toRaw(this.fileList3);
        for (let i = 0; i < tmp_list.length; i++) {
          // DONE: 对于tmp_list数组，里面的元素中的originFileObj属性才是原始的文件对象
          formData.append("images", tmp_list[i].originFileObj);
          console.log("file: ", tmp_list[i].originFileObj);
        }
      } else {
        // Notice.error("文件不能为空！")
        console.log("文件为空");
        return Upload.LIST_IGNORE;
      }

      // ↓ 在上传过程中，按钮为 loading 状态
      this.btnLoading3 = true;
      console.log("formData------: ", formData.getAll("images"));
      axios
        .post("/shop/uploadImgMultiple", formData, {
          baseURL: "http://localhost:8082",
          headers: {
            "Content-Type": "multipart/form-data",
            transformRequest: [(data) => data],
          },
        })
        .then(
          (res) => {
            console.log(res.data);
            // ↓ 上传成功，按钮为默认状态

            this.btnLoading3 = false;
            // ↓ 获取上传成功后的图片 url
            const imgUrl = res.data.data.urls;

            // ↓ 将获取到的图片 url 赋值给 imgUrl
            console.log("imgUrl: ", imgUrl);
            let tmp_str = "";
            let tmpList = this.shopInfo.icon_url.split(",");

            let tmp_list = [];
            for (let i = 0; i < tmpList.length; i++) {
              if (tmpList[i] == "") continue;
              tmp_list.push(tmpList[i]);
            }
            // if (tmp_list == [])
            // {
            for (let index in imgUrl) {
              tmp_list.push(imgUrl[index]);
            }
            tmp_str = JSON.stringify(tmp_list);
            tmp_str = tmp_str.replaceAll("\"", "");
            this.shopInfo.icon_url = tmp_str.substring(1, tmp_str.length - 1);
            // }
            console.log("this.shopInfo.icon: ", this.shopInfo.icon_url);
            alert("上传成功");
          },
          () => {
            alert("上传失败");
            this.btnLoading = false;
          }
        );
    },

    handleRemove() {
      this.fileList = null;
      // ↑ 置空待上传文件列表
      this.base64img = null;
    },
  },
};
</script>

<style scoped>
.content {
  height: 91vh;
  display: flex;
  justify-content: center;
  background-color: rgb(6, 168, 238);
}
.card {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  height: 70%;
  width: 40%;
  margin-top: 60px;
  background-color: white;
  border-radius: 12px;
}
.card text {
  font-size: 20px;
  margin: 10px 10px;
}
.btn {
  width: 100%;
  /* text-align: center; */
  justify-content: center;
}
</style>